package com.appcheck.recording.listener.impl;

import java.lang.reflect.Field;

import android.os.Build;
import android.widget.DatePicker;

import com.appcheck.recording.ListenerManager;
import com.appcheck.recording.WidgetHelper;
import com.appcheck.recording.action.impl.DateChangedAction;
import com.appcheck.recording.listener.AbstractListener;
import com.appcheck.recording.utils.Logger;

public class DateChangedListener extends AbstractListener implements DatePicker.OnDateChangedListener{

	private int b;
	private int count;
	
	public DateChangedListener(DatePicker datePicker) {
		super(datePicker, DatePicker.class, DatePicker.OnDateChangedListener.class);
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		if (this.b++ > 1) {
		      return;
		    }
		this.count += 1;
		if ((Build.VERSION.SDK_INT < 14) || (this.count % 2 == 0)){
		      DateChangedAction dateChangedAction = new DateChangedAction();
		      dateChangedAction.setYear(year);
		      dateChangedAction.setMonth(monthOfYear);
		      dateChangedAction.setDayOfMonth(dayOfMonth);
		      dateChangedAction.setResourceName(WidgetHelper.getResourceName(view));
		      dateChangedAction.setResourceId(WidgetHelper.getResourceId(view));
		      if (dateChangedAction.getResourceName() == null) {
		    	  dateChangedAction.setIndex(WidgetHelper.getCurrentIndexOfView(view));
		      }
		      ListenerManager.getListenerManager().handleAction(dateChangedAction);
		      if (this.listener != null) {
		    	  ((DatePicker.OnDateChangedListener)this.listener).onDateChanged(view, year, monthOfYear, dayOfMonth);
		      }
		      try{
		    	  Field onDateChangedListenerField = DatePicker.class.getDeclaredField("mOnDateChangedListener");
		    	  onDateChangedListenerField.setAccessible(true);
		    	  onDateChangedListenerField.set(view, this);
		      }
		      catch (Exception exception){
		    	  Logger.ERROR("Coudn't set listener on DatePicker", exception);
		      }
		      this.b = 0;
		 }
		
	}

}
